import {createSlice} from "@reduxjs/toolkit";

export const todoSlice = createSlice({
    name: 'todoList',
    initialState: {
        todos: [{id: '001', name: "吃饭", done: true}]
    },
    reducers: {
        addTodo: (state, {payload}) => {
            const flag = state.todos.some(item => payload.name === item.name);
            if (flag) {
                return alert('名称重复')
            }
            state.todos = [payload, ...state.todos]
        },
        updateTodo: (state, {payload}) => {
            const {id, done} = payload
            state.todos = state.todos.map((item) => {
                if (item.id === id) return {...item, done}
                else return item
            })
        },
        deleteTodo: (state, {payload}) => {
            state.todos = state.todos.filter((item) => {
                return item.id !== payload
            })
        },
        updateAllTodoDone: (state, {payload}) => {
            state.todos.forEach(item => item.done = payload)
        },

        clearAllDone: (state) => {
            state.todos = state.todos.filter((todoObj) => {
                return !todoObj.done
            })
        }
    }
})

export const {addTodo, updateTodo, deleteTodo, updateAllTodoDone, clearAllDone} = todoSlice.actions
export default todoSlice.reducer